package cn.tt.tuantuanerp.passport.webapi.security;


import cn.tt.tuantuanerp.passport.webapi.mapper.UserMapper;
import cn.tt.tuantuanerp.tuantuanerp.comment.pojo.vo.UserLoginInfoVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 用户详情业务实现类，专用于Spring Security，将在Spring Security执行认证时自动调用
 *
 * @author java@tedu.cn
 * @version 0.0.1
 */
@Slf4j
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        log.debug("Spring Security自动调用loadUserByUsername()方法获取用户名为【{}】的用户详情……", s);

        UserLoginInfoVO loginUser = userMapper.getLoginInfo(s);
        log.debug("从数据库中查询到的用户信息：{}", loginUser);
        if (loginUser == null) {
            String message = "登录失败，用户名不存在！";
            log.warn(message);
            throw new BadCredentialsException(message);
        }

        List<String> permissions = loginUser.getPermissions();
        List<GrantedAuthority> authorities = new ArrayList<>();
        for (String permission : permissions) {
            authorities.add(new SimpleGrantedAuthority(permission));
        }

        UserDetails userDetails = new UserDetails(
                loginUser.getUsername(), loginUser.getPassword(),
                loginUser.getEnable() == 1, authorities);
        userDetails.setId(loginUser.getId());

        log.debug("即将向Spring Security框架返回UserDetails对象：{}", userDetails);
        return userDetails;
    }

}
